const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const workboxWebpackPlugin = require('workbox-webpack-plugin');
module.exports = {
  entry: './src/main.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'built.[name].[contenthash:10].js'
  },
  mode: 'development',
  devtool: 'source-map',
  optimization: {
    splitChunks: {
      chunks: 'all'
    }
  },
  module: {
    rules: [
      {
        oneOf: [
          {
            test: /\.css$/,
            use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader']
          },
          {
            test: /\.(scss|sass)$/,
            use: [MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader', 'sass-loader']
          },
          {
            test: /\.(png|jpg|gif)$/,
            use: [
              {
                loader: 'url-loader',
                options: {
                  limit: 8192,
                  esModule: false//关闭ESModule url-loader默认用ESModule解析时候，而html-loader是commonjs,这里关闭ESModule
                }
              }
            ]
          },
          {
            test: /\.html$/,
            loader: 'html-loader'
          },
          {
            exclude: /\.(html|css|js|scss|sass|png|jpg|gif)$/,
            loader: 'file-loader',
            options: {
              name: '[path][name].[ext]'
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new MiniCssExtractPlugin({
      filename: 'built.[contenthash:10].css'
    }),//提取css为单独文件
    new OptimizeCssAssetsWebpackPlugin(),//压缩css
    new HtmlWebpackPlugin({
      title: 'webpack html',
      template: path.resolve(__dirname, 'src', 'template.html'),
      filename: 'index.html',
      minify: {//压缩选项
        removeComments: true,//去注释
        collapseWhitespace: true,//去空白符换行
        minifyCss: true//压缩内联样式
      }
    }),
    new workboxWebpackPlugin.GenerateSW({
      clientsClaim: true,
      skipWaiting: true
    })
  ],
  devServer: {
    //项目路径
    contentBase: path.resolve(__dirname, 'dist'),
    //启动gzip压缩
    compress: true,
    //端口号
    port: 8000,
    //自动打开浏览器
    open: true,
    //开启HMR
    hot: true
  }
}